package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.OrderBill;
import cn.wolfcode.wms.domain.OrderBillItem;
import cn.wolfcode.wms.mapper.OrderBillMapper;
import cn.wolfcode.wms.mapper.OrderBillItemMapper;
import cn.wolfcode.wms.page.PageResult;
import cn.wolfcode.wms.query.QueryObject;
import cn.wolfcode.wms.service.IOrderBillService;
import cn.wolfcode.wms.util.UserContext;
import cn.wolfcode.wms.web.exception.LogicalException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

@Service
public class OrderBillServiceImpl implements IOrderBillService {
    @Autowired
    private OrderBillMapper billMapper;
    @Autowired
    private OrderBillItemMapper itemMapper;

    public void save(OrderBill orderBill) {
        billMapper.insert(orderBill);
    }

    public void delete(long id) {
        OrderBill orderBill = billMapper.selectByPrimaryKey(id);
        if (orderBill.getStatus() != 0) {
            itemMapper.deleteByBillId(id);
            billMapper.deleteByPrimaryKey(id);
        }else{
            throw new LogicalException("该订单已审核无法删除!");
        }
    }

    public void update(OrderBill orderBill) {
        billMapper.updateByPrimaryKey(orderBill);
    }

    public OrderBill get(long id) {
        return billMapper.selectByPrimaryKey(id);
    }

    public List<OrderBill> list() {
        return billMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int rows = billMapper.queryForCount(qo);
        if (rows == 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List<?> result = billMapper.queryForList(qo);
        return new PageResult(result, rows, qo.getCurrentPage(), qo.getPageSize());
    }

    public void saveOrUpdate(OrderBill orderBill) {
        if (orderBill.getId() == null) {
            saveBill(orderBill);
        } else {
            updateBill(orderBill);
        }
    }

    public void audit(Long id) {
        OrderBill orderBill = billMapper.selectByPrimaryKey(id);
        if (orderBill.getStatus() != OrderBill.STATUS_AUDITED) {
            orderBill.setAuditor(UserContext.getCurrentUser());
            orderBill.setAuditTime(new Date());
            orderBill.setStatus(OrderBill.STATUS_AUDITED);
            billMapper.audit(orderBill);
        }else{
            throw new LogicalException("订单已经审核!");
        }
    }

    private void updateBill(OrderBill orderBill) {
        //根据传入的ID去查数据库当中的订单的状态
        OrderBill oldBill = billMapper.selectByPrimaryKey(orderBill.getId());
        //当订单状态为未审核状态的时候才执行更行
        if (oldBill.getStatus() == 0) {
            //1.删除原来订单中所有的订单明细
            itemMapper.deleteByBillId(oldBill.getId());
            //2.重新计算订单中的总数量和总价格
            BigDecimal totalNumber = BigDecimal.ZERO;
            BigDecimal totalAmount = BigDecimal.ZERO;
            for (OrderBillItem billItem : orderBill.getItems()) {
                BigDecimal number = billItem.getNumber();
                BigDecimal costPrice = billItem.getCostPrice();
                BigDecimal amount = number.multiply(costPrice).setScale(2, RoundingMode.HALF_UP);
                billItem.setAmount(amount);
                totalNumber = totalNumber.add(number);
                totalAmount = totalAmount.add(amount);
                billItem.setBillId(oldBill.getId());
                itemMapper.insert(billItem);
            }
            oldBill.setTotalNumber(totalNumber);
            oldBill.setTotalAmount(totalAmount);
            oldBill.setSn(orderBill.getSn());
            oldBill.setVdate(orderBill.getVdate());
            oldBill.setSupplier(orderBill.getSupplier());
            billMapper.updateByPrimaryKey(oldBill);
        }else{
            throw new LogicalException("订单已经审核无法更新");
        }
    }

    public void saveBill(OrderBill orderBill) {
        BigDecimal totalNumber = BigDecimal.ZERO;
        BigDecimal totalAmount = BigDecimal.ZERO;
        //设置订单的状态
        orderBill.setStatus(OrderBill.STATUS_NORMAL);
        //设置录入人
        orderBill.setInputUser(UserContext.getCurrentUser());
        //设置录入时间
        orderBill.setInputTime(new Date());
        //保存明细
        List<OrderBillItem> items = orderBill.getItems();
        for (OrderBillItem item : items) {
            BigDecimal number = item.getNumber();
            BigDecimal costPrice = item.getCostPrice();
            BigDecimal amount = number.multiply(costPrice).setScale(2, RoundingMode.HALF_UP);
            item.setAmount(amount);
            totalNumber = totalNumber.add(number);
            totalAmount = totalAmount.add(amount);
        }
        orderBill.setTotalNumber(totalNumber);
        orderBill.setTotalAmount(totalAmount);
        //保存订单
        billMapper.insert(orderBill);
        for (OrderBillItem item : items) {
            item.setBillId(orderBill.getId());
            itemMapper.insert(item);
        }
    }
}
